/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContext;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;

/**
 *
 * @author Gjun
 */
@WebServlet(name = "UploadServlet", urlPatterns = {"/UploadServlet"})
public class UploadServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet UploadServlet</title>");            
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet UploadServlet at " + request.getContextPath() + "</h1>");
            out.println("</body>");
            out.println("</html>");
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        	response.setCharacterEncoding("UTF-8");
		response.getWriter().println("請以 POST 方式上傳檔案");
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        File file=null;
        String id="";
       
        ServletContext sc=request.getServletContext();
       // String realPath=sc.getRealPath("/productPic/魚.png");
        DiskFileUpload diskFileUpload = new DiskFileUpload();
        try {
			// 將 解析的結果 放置在 List 中
             List<FileItem> list = diskFileUpload.parseRequest(request);
             
               for(FileItem fileItem : list){
                   if(fileItem.isFormField()){
					// 如果是 文字域  
                       
					
					
				}
				else{
                       if("id".equals(fileItem.getFieldName())){
						// 如果該 FileItem 名稱為 description1
					//	out.println("檢查到 description1 ... <br/>");
						
                                               String name = new File(fileItem.getName()).getName();
                           try {
                               fileItem.write( new File(File.separator + name));
                           } catch (Exception ex) {
                               Logger.getLogger(UploadServlet.class.getName()).log(Level.SEVERE, null, ex);
                           }

                    id = (request.getParameter("id"));
                   

					}
                            if("file".equals(fileItem.getFieldName())){
			File remoteFile = new File(new String(fileItem.getName().getBytes(), "UTF-8"));
						
					//	out.print(" 服務器端檔案，放在 upload 檔案夾下");
                                                 String realPath=sc.getRealPath("/productPic/"+id+".png");
						file = new File(realPath);
						
						file.createNewFile();
						
						// 寫檔案，將 FileItem 的檔案內容寫到檔案中
						InputStream ins = fileItem.getInputStream();
						OutputStream ous = new FileOutputStream(file);
						
						try{
							byte[] buffer = new byte[1024]; 
							int len = 0;
							while((len=ins.read(buffer)) > -1)
								ous.write(buffer, 0, len);
							
						}finally{
							ous.close();
							ins.close();
						}
					}
                   }
					
               }			
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
		e.printStackTrace();
                  
		}
        if(file != null){
		//out.println("		<div class='line'>");
		//out.println("			<div align='left' class='leftDiv'>file1：</div>");
		//out.println("			<div align='left' class='rightDiv'>");
		//out.println("				<a href='" + request.getContextPath() + "/attachment/" + file.getName() + "' target=_blank>" + file.getName() +  "</a>"	);
		//out.println("			</div>");
		//out.println("		</div>");
		}
        request.setAttribute("id",id);
        request.getRequestDispatcher("commupdate.jsp").forward(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
